<?php

namespace App\Constant\User;

use App\Constant\Enum;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;

class UserEntity
{
    /** @var string */
    private $username;

    /** @var string */
    private $nickname;

    /** @var string */
    private $password;

    /** @var string */
    private $phone;

    /** @var string */
    private $avatar;

    /** @var string */
    private $openid;

    private $attributes = [];

    public function __construct(array $attributes = [])
    {
        $this->username = $attributes['username'] ?? '';
        $this->password = $attributes['password'] ?? '';
        $this->nickname = $attributes['nickname'] ?? '';
        $this->phone = $attributes['phone'] ?? '';
        $this->avatar = $attributes['avatar'] ?? '';
        $this->openid = $attributes['openid'] ?? '';

        if (empty($this->openid)) {
            throw new \Exception('Invalid userinfo');
        }

        $this->attributes = $attributes;
    }


    public function toArray(): array
    {
        return array_merge($this->attributes, [
            'username' => $this->username,
            'password' => !empty($this->password) ? Hash::make($this->password) : '',
            'nickname' => $this->nickname,
            'phone' => $this->phone,
            'avatar' => $this->avatar,
            'openid' => $this->openid,
            'status' => Enum::STATUS_ENABLED,
            'registered_at' => Carbon::now(),
        ]);
    }

    /**
     * @return mixed|string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @return mixed|string
     */
    public function getNickname()
    {
        return $this->nickname;
    }

    /**
     * @return mixed|string
     */
    public function getPhone()
    {
        return $this->phone;
    }

    /**
     * @return mixed|string
     */
    public function getAvatar()
    {
        return $this->avatar;
    }

    /**
     * @return mixed|string
     */
    public function getOpenid()
    {
        return $this->openid;
    }
}
